import json
import mitmproxy
from mitmproxy import http, ctx


class Events:
    def request(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP request has been read.
            https://stock.xueqiu.com/v5/stock/batch/quote.json?_t=1NETEASE55d7e8578966f744d5452096654f6f42.4558458945.1624970447480.1624971747547&_s=250a2c&x=0.51&symbol=SZ300339%2CMF%2CSH600702%2CSZ300059%2CSH601919%2CBABA%2CSH601318&extend=detail
        """
        # 可以在request请求中实现maplocal操作
        # if "quote.json" in flow.request.pretty_url:
        #     with open ("quote.json",encoding="utf-8") as f:
        # 读取f文件的内容, 响应
        #         flow.response = http.HTTPResponse.make(200, f.read(),{"content-type": "application/json"})


    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP response has been read.
            实现rewrite
        """
        if "quote.json" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            # 打印响应数据体
            ctx.log.info(str(flow.response.content))
            # 把响应数据保存到data 中
            data = json.loads(flow.response.content)
            with open ("data.json", "w", encoding="utf-8") as f:
                f.write(str(data))
                # 用边界值方法修改股票百分比
                data['data']['items'][0]['quote']['percent'] = "-999999.999999"
                data['data']['items'][1]['quote']['percent'] = "-3.5658"
                data['data']['items'][2]['quote']['percent'] = "-0.0001"
                data['data']['items'][3]['quote']['percent'] = "-0.000001"
                data['data']['items'][4]['quote']['percent'] = "0.00"
                data['data']['items'][5]['quote']['percent'] = "0.0001"
                data['data']['items'][6]['quote']['percent'] = "0.000001"
                data['data']['items'][7]['quote']['percent'] = "8.8888"
                data['data']['items'][8]['quote']['percent'] = "999999.999999"
                # 把修改后的内容赋值给response 数据
                flow.response.text = json.dumps(data)

# 实例化请求
addons = [
    Events()
]

if __name__ == '__main__':
    from mitmproxy.tools._main import mitmdump
    mitmdump(['-s','mitm_xueqiu.py', '-p','8080'])

